/**
 * SessionFilter.java
 * Created at 2016-5-5
 * Created by TangSanlin
 * Copyright (C) 2016 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.session;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * <p>
 * ClassName: SessionFilter
 * </p>
 * <p>
 * Description: session过滤器
 * </p>
 * <p>
 * Author: TangSanlin
 * </p>
 * <p>
 * Date: 2016-5-17
 * </p>
 */
public class SessionFilter implements Filter {
    /**
     * 排除的过滤标识，配置的参数名称
     */
    private static final String PARAMNAME = "login";
    
    /**
     * 日志信息
     */
    private static Logger logger = LoggerFactory.getLogger(SessionFilter.class);

    /**
     * 排除的过滤标识，参数值
     */
    private String paramValue;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.paramValue = filterConfig.getInitParameter(PARAMNAME);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest req;
        req = (HttpServletRequest) request;
        HttpServletResponse res;
        res = (HttpServletResponse) response;

        String referer;
        referer = req.getHeader("Referer");

        String serverName;
        serverName = request.getServerName();
        if (null != referer && referer.indexOf(serverName) < 0) {
            req.getRequestDispatcher("login.jsp").forward(req, response);
            return;
        }
        String uri;
        uri = req.getRequestURI();

        /** 拦截所有的/main，/forwardPage.mvc，.jsp请求 */
        boolean uriExistsMain;
        uriExistsMain = uri.indexOf("/main") > -1;
        boolean uriExistsForwarPage;
        uriExistsForwarPage = uri.indexOf("/forwardPage.mvc") > -1;
        boolean uriExistsJsp;
        uriExistsJsp = uri.indexOf(".jsp") > 1;
        boolean uriIsAppReq;
        uriIsAppReq = uri.indexOf("/app/") > 1;
        //if (uriExistsMain || uriExistsForwarPage || uriExistsJsp) {
        if (uriExistsForwarPage || uriExistsJsp) {
            boolean uriNotLogin;
            uriNotLogin = (uri.indexOf(this.paramValue) == -1 && (uri.indexOf("checkLoginStatus") == -1));
            if (uriNotLogin) {
                SessionManage sm;
                sm = SessionManage.getSessionManage();
                HttpSession session;
                session = req.getSession(false);
                if (session == null) {
                    this.forwardLoginPage(req, res);
                    return;

                }
                UserSession userSession;
                userSession = sm.getUserSession(session);
                if (userSession == null) {
                    this.forwardLoginPage(req, res);
                    return;
                } else {
                    if (userSession.getUserId() == null) {
                        this.forwardLoginPage(req, res);
                        return;
                    }
                    session.setAttribute(SessionManage.USERSESSION, userSession);
                }
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * 
     * <p>
     * Description: 跳转到登录页面
     * </p>
     * 
     * @param request 请求
     * @param response 响应
     * @throws IOException IO异常
     * @throws ServletException ServletException
     */
    private void forwardLoginPage(HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException {
        String xRequestedWith;
        xRequestedWith = request.getHeader("x-requested-with") ;
        if (xRequestedWith != null) {
            //response.getWriter().write("eval(\"window.location.href='login.jsp'\")");
            response.setHeader("sessionstatus", "timeout");
        } else {
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }


    @Override
    public void destroy() {
    }

}
